package com.my.financial.repository;

import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.my.financial.domain.FinancialAccount;

@Repository
public class FinancialAccountRepository {
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}
	
	public void save(FinancialAccount account){
		getSession().save(account);
	}
	
	public void delete(FinancialAccount financialAccount) {
		getSession().delete(financialAccount);
	}
	
	public void update(FinancialAccount account){
		getSession().update(account);
	}
	
	public FinancialAccount findById(Long accountId) {
		return (FinancialAccount) this.getSession().get(FinancialAccount.class, accountId);
	}

	public FinancialAccount findByIdOnLockMode(long l) {
		return (FinancialAccount) this.getSession().get(FinancialAccount.class, l,new LockOptions(LockMode.PESSIMISTIC_WRITE));
	}
	
	@SuppressWarnings("unchecked")
	public List<FinancialAccount> findAllAccount(Long userId) {
		Query query = this.getSession().createQuery("from "+FinancialAccount.class.getName()+" where user_id = :userId");
		query.setParameter("userId", userId);
		return query.list();
	}
}
